<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\api\controller\Phase;
use app\common\controller\Backend;
use app\common\model\Hospital;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Response;

/**
 * 设备管理
 *
 * @icon fa fa-circle-o
 */
class Equipment extends Backend
{

    /**
     * Equipment模型对象
     * @var \app\common\model\Equipment
     */
    protected $model = null;
    protected $Ids = null;
    protected $user = null;
    protected $modelValidate  = true;   //是否开启validate 验证默认是fasle 关闭状态

    protected $modelSceneeVaildate = true;  //是否开启模型场景验证默认是false 关闭状态  （模型场景）
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Equipment;
        $this->view->assign("enclosureDataList", $this->model->getEnclosureDataList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->Ids=$this->auth->getGroupIds();
        $this->user=$this->auth->getUserInfo();
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where1="1=1";
            if($this->Ids[0]==2) {
                $admin = Admin::get($this->user["id"]);
                if ($admin) {
                    $where1 = ["account" => $admin["username"]];
                    $hospital = Hospital::field("id")->where(["status" => 1])
                        ->where('FIND_IN_SET("' . $this->user["id"] . '", admin_ids)')->find();
                    $where1=["department.hospital_id"=>$hospital["id"]];
                }
            }
            $where7="1=1";
            if($this->request->param('sb')){
                $sb=$this->request->param('sb');
                $fh="<";
                if ($sb==1) $fh=">";
                $where7="equipment.id IN(
SELECT id FROM (SELECT 
 SUBSTR(SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTR(JSON_EXTRACT(a.next_json,'$[*].time'),2,LENGTH(JSON_EXTRACT(a.next_json,'$[*].time'))-2), ', ', b.help_topic_id + 1) ,', ', -1),2,10) AS TIME,a.id
FROM
 yl_equipment a JOIN mysql.help_topic b 
 ON 
 b.help_topic_id < LENGTH(JSON_EXTRACT(a.next_json,'$[*].time')) - LENGTH(REPLACE(JSON_EXTRACT(a.next_json,'$[*].time'),',','')) + 1) c WHERE c.time ".$fh
                    ." DATE_FORMAT( NOW(),'%Y-%m-%d'))";
            }
            $list = $this->model
                    ->with(['department'])
                    ->field("a.name 'a.name',a.id 'a.id'")
                    ->join("hospital a","a.id=equipment.hospital_id",'left')
                    ->where($where)
                    ->where($where1)
                    ->where($where7)
                    ->order($sort, $order)
                    ->paginate($limit);
            foreach ($list as $row) {
                /*$row->visible(['id','name','next','a.id','a.name','marking','serial','enclosure_data','enclosure','software_version','next_json','image','createtime','status','remark']);
                $row->visible(['department']);*/
				$row->getRelation('department')->visible(['name']);
				$next_json=json_decode($row["next_json"],true);
                if($next_json){
                    $phase=new Phase();
                    $next=$phase->find_closest($next_json, date("Y-m-d",time()));
                    $row["next"]=$next?$next:$next_json[count($next_json)-1]["time"];
                }
            }

            $key_admin=false;
         if($this->Ids[0]==2) {
                $admin = Admin::get($this->user["id"]);
                if ($admin) {
                    $where2 = ["account" => $admin["username"]];
                    $hospital = Hospital::field("id")->where(["status" => 1])
                        ->where('FIND_IN_SET("' . $this->user["id"] . '", admin_ids)')->find();
                    if($hospital) $key_admin=true;
                }
            }
            $result = array("total" => $list->total(), "rows" => $list->items(),'key_admin'=>$key_admin);

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $next=json_decode($params["next_json"],true);
                if(!empty($next)){
                    sort($next);
                    $params["next_json"]=json_encode($next);
                    $next2=$this->array_unset($next,"time");
                    if(count($next)!=count($next2)){
                        $this->error("请删除相同时间的元素");
                    }
                }
                Db::startTrans();
                try {
                    $this->modelValidate = true;
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params["createtime"]=time();
                    if(!empty($params["start_time"])) $params["start_time"]=strtotime($params["start_time"]);
                    $result = $this->model->allowField(true)->insertGetId($params);
                    $text = "http://ylsbr.westts.cn/?id=".$result;
                    $qrInfo = $this->buildQrcode($text,$result);//$userInfo['nickname']);
                    $this->model->where(["id"=>$result])->update(["image"=>$qrInfo]);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $hospital_id=0;
        if($this->Ids[0]==2) {
            $admin = Admin::get($this->user["id"]);
            if ($admin) {
                $hospital = Hospital::field("id")->where(["status" => 1])->where('FIND_IN_SET("' . $this->user["id"] . '", admin_ids)')->find();
                $hospital_id=$hospital["id"];
            }
        }
        $this->assign("hospital_id",$hospital_id);
        return $this->view->fetch();
    }
    // 生成二维码
    public function buildQrcode($text,$label)
    {
        $params = [
            'text'           => $text,
            'label'           => $label,
            'size'           => 350,    //大小
            'padding'        => 15,    //内边距
            'errorlevel'     => 'medium',   //容错级别:low-低   medium-中等   quartile-高   high-超高
            'foreground'     => "#000000",     //前景色
            'background'     => "#ffffff",  //背景色
            'logo'           => 0,    //Logo:1-显示，0-不显示
            'logosize'       => '',  //Logo大小
            'labelfontsize'  => 14, //标签大小
            'labelalignment' => 'center',    //标签水平位置:left-左  center-中   right-右
        ];

        $qrCode = \addons\qrcode\library\Service::qrcode($params);
        $response = Response::create()->header("Content-Type", "image/png");

        // 直接显示二维码
        /* header('Content-Type: ' . $qrCode->getContentType());
         $response->content($qrCode->writeString());*/

        // 写入到文件
        $fileUrl = '/uploads/qrcode/equipment/' . $label . '.png';
        $filePath = ROOT_PATH .'public'. $fileUrl;
        if (!file_exists(ROOT_PATH .'public/uploads/qrcode/')) mkdir (ROOT_PATH .'public/uploads/qrcode/',0777,true);
        if (!file_exists(ROOT_PATH .'public/uploads/qrcode/equipment/')) mkdir (ROOT_PATH .'public/uploads/qrcode/equipment/',0777,true);

        $qrCode->writeFile($filePath);

        $filePath=cdnurl(".".$fileUrl);
        return $filePath;
    }

    /**
     * 使用in_array()对两个二维数组取差集
     *  - 去除$arr1 中 存在和$arr2相同的部分之后的内容
     * @param $arr1
     * @param $arr2
     * @return array
     */
    function get_diff_array_by_filter($arr1,$arr2)
    {
        try {
            return array_filter($arr1, function ($v) use ($arr2) {
                return !in_array($v, $arr2);
            });
        } catch (\Exception $exception) {
            return $arr1;
        }
    }
    function array_unset($arr,$key){ //$arr->传入数组 $key->判断的key值
//建立一个目标数组
        $res = array();
        foreach ($arr as $value) {
//查看有没有重复项
            if(isset($res[$value[$key]])){
//有：销毁
                unset($value[$key]);
            }else{
                $res[$value[$key]] = $value;

            }
        }
        return $res;

    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $count=json_decode($row["next_json"],true);
        $row["count"]=$count;
        $count=count($count);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                $next=json_decode($params["next_json"],true);
                if(!empty($next)){
                    $next2=$this->array_unset($next,"time");
                    if(count($next)!=count($next2)){
                        $this->error("请删除相同时间的元素");
                    }
                    $i=$this->get_diff_array_by_filter($next,$row["count"]);
                    sort($next);
                    $params["next_json"]=array_merge($row["count"],$next);
                    if(count($i)!=count($next)){
                        $this->error("请删除相同时间的元素");
                    }
                    $params["next_json"]=json_encode($params["next_json"]);
                }
                Db::startTrans();
                try {
                    $this->modelValidate = true;
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    if(!empty($params["start_time"])) $params["start_time"]=strtotime($params["start_time"]);
                    $result = $row->allowField(true)->save($params);
                    $service_data=[];
                    $warranty=\app\common\model\work\Warranty::where(["equipment_id"=>$ids,"type_data"=>1])->whereIn("status",["0","1"])->select();//未完成的工单
                    if($warranty){
                        $time=time();
                        /*foreach ($next as $key => $v)
                        {
                            $service_time=strtotime($v["time"]."00:00:00");
                            $v_time=strtotime(date("Y-m-d")."00:00:00");
                            if($service_time>$v_time)
                            {
                                foreach ($warranty as $ks=>$vs){
                                    $service_data[$key]["warranty_id"]=$vs["id"];
                                    $service_data[$key]["servicetime"]=$service_time;
                                    $service_data[$key]["type_data"]=$vs["type_data"];
                                    $service_data[$key]["user_id"]=$vs["user_id"];
                                    $service_data[$key]["createtime"]=$time;
                                    $service_data[$key]["status"]='0';
                                    $service_data[$key]["number"]=$vs["number"]+$v+1;
                                }
                            }
                        }*/
                        /*$num=count($next);
                        foreach ($warranty as $ks=>$vs){
                            foreach ($next as $key => $v)
                            {
                                $service_time=strtotime($v["time"]."00:00:00");
                                $v_time=strtotime(date("Y-m-d")."00:00:00");
                                if($service_time>$v_time)
                                {
                                    $service_data[$ks]["warranty_id"]=$vs["id"];
                                    $service_data[$ks]["servicetime"]=$service_time;
                                    $service_data[$ks]["type_data"]=$vs["type_data"];
                                    $service_data[$ks]["user_id"]=$vs["user_id"];
                                    $service_data[$ks]["createtime"]=$time;
                                    $service_data[$ks]["status"]='0';
                                    $service_data[$ks]["number"]=$vs["number"]+$key+1;
                                    if($key+1==$num){
                                        //最后一个
                                        \app\common\model\work\Warranty::where(["id"=>$vs["id"]])->update(["number"=>$service_data[$key]["number"],"status"=>'1']);
                                    }
                                }
                            }
                        }*/
                    }
                    /*if($service_data){
                        \app\common\model\work\Service::insertAll($service_data);//记录下次维修时间
                    }*/
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $hospital_id=0;
        if($this->Ids[0]==2) {
            $admin = Admin::get($this->user["id"]);
            if ($admin) {
                $hospital = Hospital::field("id")->where(["status" => 1])->where('FIND_IN_SET("' . $this->user["id"] . '", admin_ids)')->find();
                $hospital_id=$hospital["id"];
            }
        }
        $this->assign("hospital_id",$hospital_id);
        $this->view->assign("row", $row);
        $this->view->assign("count", $count);
        return $this->view->fetch();
    }

    /**
     * 新增
     * */
    public function selectpage2()
    {
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        $datalist = $this->model
            ->whereLike("name","%".$this->request->param("name")."%")
            ->where(["department_id"=>$this->request->param("department_id")])
            ->page($page, $pagesize)
            ->select();
        $total = $this->model
            ->whereLike("name","%".$this->request->param("name")."%")
            ->where(["department_id"=>$this->request->param("department_id")])
            ->count();
        return json(['list' => $datalist, 'total' => $total]);
    }
}
